package com.qr.controller;

import com.qr.constant.Constant;
import com.qr.result.Result;
import com.qr.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RestController
@Slf4j
public class CommonController {

    @Autowired
    private AliOssUtil aliOssUtil;

    /**
     * 上传图片到oss
     */
    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file) {
        try {
            // 保证名字唯一，对名字进行处理
            String extension = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            String fileName = UUID.randomUUID() + extension;
            String uploadUrl = aliOssUtil.upload(file.getBytes(), fileName);
            return Result.success(uploadUrl,Constant.UPLOAD_SUCCESS);
        } catch (IOException e) {
            log.error("上传文件失败", e);
        }
        return Result.error(Constant.UPLOAD_FAILED);
    }
}
